import 'package:flutter/material.dart';

class DropDownMenuRoute extends PopupRoute {
  final Rect position; //指定下拉菜单相对于按钮或其他元素的位置
  final double menuHeight; //显示下拉框高
  final double itemHeight; // 每个Item的高
  final double fPosX; //X轴偏移量
  final Function(dynamic data)? clickBack;
  final Function()? popBack;
  final List<String> mlist;
  final int iSelTag; //选中

  DropDownMenuRoute({
    required this.position,
    this.menuHeight = 120,
    this.fPosX = 0,
    this.clickBack,
    this.popBack,
    required this.mlist,
    this.itemHeight = 40,
    this.iSelTag = -1,
  });

  @override
  Color? get barrierColor => null;

  @override
  bool get barrierDismissible {
    return true;
  }

  @override
  String? get barrierLabel => null;

  @override
  Widget buildPage(BuildContext context, Animation<double> animation,
      Animation<double> secondaryAnimation) {
    return _DropDownMenuRouteWidget(
      position: position,
      menuHeight: menuHeight,
      itemHeight: itemHeight,
      fPosX: fPosX,
      clickBack: clickBack,
      popBack: popBack,
      mlist: mlist,
      iSelTag: iSelTag,
      animation:
          animation, // Pass the animation parameter to _DropDownMenuRouteWidget
    );
  }

  @override
  Duration get transitionDuration => Duration(milliseconds: menuHeight.toInt());
}

class _DropDownMenuRouteWidget extends StatefulWidget {
  final Rect position; //指定下拉菜单相对于按钮或其他元素的位置
  final double menuHeight; //显示下拉框高
  final double itemHeight; // 每个Item的高
  final double fPosX; //X轴偏移量
  final Function(dynamic data)? clickBack;
  final Function()? popBack;
  final List<String> mlist;
  final int iSelTag; //选中
  final Animation<double> animation; // Animation parameter

  const _DropDownMenuRouteWidget({
    Key? key,
    required this.position,
    this.menuHeight = 120,
    this.itemHeight = 40,
    this.fPosX = 0,
    this.clickBack,
    this.popBack,
    required this.mlist,
    this.iSelTag = -1,
    required this.animation, //animation parameter
  }) : super(key: key);

  @override
  _DropDownMenuRouteWidgetState createState() =>
      _DropDownMenuRouteWidgetState();
}

class _DropDownMenuRouteWidgetState extends State<_DropDownMenuRouteWidget> {
  late ScrollController _scrollController;

  @override
  void initState() {
    super.initState();
    _scrollController = ScrollController();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      //_scrollToIndex(widget.iSelTag);
      // Future.delayed(const Duration(milliseconds: 100), () {
      //   _scrollToIndex(widget.iSelTag);
      // });

      WidgetsBinding.instance.addPostFrameCallback((_) {
        _scrollToIndex(widget.iSelTag);
      });
    });
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  void _scrollToIndex(int index) {
    if (index >= 0 && index < widget.mlist.length) {
      //double maxOffset = _scrollController.position.maxScrollExtent;
      double offset = index * widget.itemHeight + index * 0.5;
      //_scrollController.jumpTo(offset);

      // _scrollController.animateTo(
      //   offset,
      //   duration: const Duration(milliseconds: 300),
      //   curve: Curves.easeInOut,
      // );

      double maxScroll = _scrollController.position.maxScrollExtent;
      _scrollController.animateTo(
        offset > maxScroll ? maxScroll : offset, // 避免超出最大滚动范围
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeInOut,
      );
    }
  }

  // void _scrollToIndex(int index) {
  //   if (index >= 0 && index < widget.mlist.length) {
  //     double offset = index * widget.itemHeight;
  //     _scrollController.animateTo(
  //       offset,
  //       duration: const Duration(milliseconds: 300),
  //       curve: Curves.easeInOut,
  //     );
  //   }
  // }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        // if (widget.popBack != null) {
        //   widget.popBack!();
        // }
        // Navigator.pop(context);

        widget.popBack?.call();
        if (Navigator.canPop(context)) {
          Navigator.pop(context);
        }
      },
      child: CustomSingleChildLayout(
        delegate: _DropDownMenuRouteLayout(
          position: widget.position,
          menuHeight: widget.menuHeight,
          fPosX: widget.fPosX,
        ),
        child: SizeTransition(
            sizeFactor:
                Tween<double>(begin: 0.0, end: 1.0).animate(widget.animation),
            child: Material(
              //elevation: 6, // 提供阴影
              borderRadius: BorderRadius.circular(12),
              color: Colors.white,
              // decoration: BoxDecoration(
              //   color: Colors.white, // 背景色
              //   borderRadius: BorderRadius.circular(12), // 圆角
              //   boxShadow: [
              //     BoxShadow(
              //       color: Colors.black.withOpacity(0.2), // 阴影颜色
              //       blurRadius: 6, // 模糊半径
              //       spreadRadius: 2, // 扩散半径
              //       offset: Offset(2, 4), // 偏移量 (x, y)
              //     ),
              //   ],
              // ),
              child: MediaQuery.removePadding(
                removeTop: true,
                context: context,
                child: Scrollbar(
                  controller: _scrollController,
                  child: ListView.separated(
                    separatorBuilder: (BuildContext context, int index) {
                      return const Divider(
                        //color: Colors.grey.withOpacity(0.3),
                        color: Color.fromRGBO(128, 128, 128, 0.3),
                        thickness: 0.5,
                        indent: 15,
                        endIndent: 15,
                      );
                    },
                    controller: _scrollController,
                    itemCount: widget.mlist.length,
                    itemBuilder: (context, index) {
                      // final itemHeight = widget.itemHeight +
                      //     0.5;
                      // print('Item at index $index has height: $itemHeight');

                      return InkWell(
                        highlightColor: Colors.transparent,
                        splashColor: Colors.transparent,
                        onTap: () {
                          if (widget.clickBack != null) {
                            widget.clickBack!(index);
                          }
                          Navigator.of(context).pop();
                        },
                        child: Container(
                          height: widget.itemHeight,
                          alignment: Alignment.center,
                          child: Text(
                            widget.mlist[index],
                            style: TextStyle(
                              fontSize: 16,
                              color: widget.iSelTag != index
                                  ? const Color(0xFF2B3039)
                                  : Colors.blue,
                            ),
                          ),
                        ),
                      );
                    },
                  ),
                ),
              ),
            )),
      ),
    );
  }
}

class _DropDownMenuRouteLayout extends SingleChildLayoutDelegate {
  final Rect position;
  final double menuHeight;
  final double fPosX;

  _DropDownMenuRouteLayout({
    required this.position,
    required this.menuHeight,
    this.fPosX = 0,
  });

  @override
  BoxConstraints getConstraintsForChild(BoxConstraints constraints) {
    return BoxConstraints.loose(
      Size(position.right - position.left, menuHeight),
    );
  }

  @override
  Offset getPositionForChild(Size size, Size childSize) {
    return Offset(fPosX, position.bottom + 3);
  }

  // @override
  // bool shouldRelayout(SingleChildLayoutDelegate oldDelegate) {
  //   return true;
  // }

  @override
  bool shouldRelayout(covariant _DropDownMenuRouteLayout oldDelegate) {
    return position != oldDelegate.position ||
        menuHeight != oldDelegate.menuHeight ||
        fPosX != oldDelegate.fPosX;
  }
}
